//
//  HRHearViewController.m
//  Hear
//
//  Created by mac on 2017/7/6.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRHearViewController.h"
#import "HRShowRecordView.h"
#import "HRRecordAudioViewController.h"
#import "HRSearchUsersViewController.h"
#import "HRVoiceSliderView.h"
#import "RFLayout.h"
#import "HRHearCollectionViewCell.h"
#import "HRMainViewModel.h"
#import "HRMainRootModel.h"
#import "Track.h"
#import "DOUAudioStreamer.h"
#import "MBProgressHUD+assistant.h"
#import "HRDynamicViewController.h"
#import "HRPostSoundModel.h"
#import "HRPostSoundViewModel.h"
#import "HRSoundCoverViewController.h"
#import "HRSearchToolView.h"
#import "UIButton+SSEdgeInsets.h"
#import "HRChangeBackImageViewController.h"
#import "HRUpdataUserInfoModel.h"
#import "UIButton+SSEdgeInsets.h"
#import "HRHearRootTopView.h"
#import "HRFollowDyanmicInfoViewController.h"
#import "EmitterBtn.h"
#import "HRHearRootTitleTypeView.h"
#import "HRHearTopicRootViewController.h"

static void *kStatusKVOKey = &kStatusKVOKey;
static void *kDurationKVOKey = &kDurationKVOKey;
static void *kBufferingRatioKVOKey = &kBufferingRatioKVOKey;

@interface HRHearViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property(nonatomic, strong)HRHearRootTopView *topView;
@property(nonatomic, strong)UIButton *playButton;
@property(nonatomic, strong)UIButton *nickNameLabel;
@property(nonatomic, strong)UICollectionView *myCollectionView;
@property (nonatomic, assign)NSInteger pIndex;
@property (nonatomic, strong)HRMainViewModel *mainViewModel;
@property(nonatomic, strong)NSMutableArray *contentArray;
@property(nonatomic, strong)DOUAudioStreamer *streamer;
@property (nonatomic) BOOL musicIsPlaying;
@property (nonatomic) NSTimer *musicDurationTimer;
@property (nonatomic) NSInteger currentIndex;
@property(nonatomic, strong)UIButton *closeButton;
@property(nonatomic, strong)UIButton *messageButton;
@property(nonatomic, strong)EmitterBtn *likeButton;
@property(nonatomic, strong)UILabel *distanceLabel;
@property(nonatomic, strong)UILabel *leftLineLabel;
@property(nonatomic, strong)UILabel *rightLineLabel;
@property(nonatomic, strong)UIButton *titileButton;

@property(nonatomic, strong)HRMainRootModel *currentModel;

@property (nonatomic, strong)HRPostSoundViewModel *soundViewModel;

@property(nonatomic, assign)int SortType;

@property(nonatomic, assign)int Sex;

@property(nonatomic, copy)NSString *currentSexStr;

@property(nonatomic, assign)CGRect likeRect;

@property(nonatomic, assign)BOOL isLoadGuide;

@property(nonatomic, assign)BOOL isFirstLoad;

@property(nonatomic, assign)NSUInteger currentAnswerPage;
@property(nonatomic, strong)UIView *bottomView;
@property(nonatomic, strong)UIImageView *blankImageView;
@property(nonatomic, copy)NSString *QuestionID;

@property(nonatomic, assign)NSUInteger fromSearchPage;
@property(nonatomic, assign)BOOL currentPlayStatus;
@property(nonatomic, strong)HRHearRootTitleTypeView *titleTypeView;

@property(nonatomic, copy)NSString *ParentQuestionID;
@property(nonatomic, strong)UILabel *lineCoundLabel;

@property(nonatomic, assign)int currentTopicIndex;

@end

@implementation HRHearViewController

#pragma mark - Get and Set
- (UIImageView *)blankImageView{
    if (_blankImageView == nil) {
        _blankImageView = [[UIImageView alloc] init];
        _blankImageView.image = [UIImage imageNamed:@"没有此话题用户的状态下"];
        [self.view addSubview:self.blankImageView];
        _blankImageView.userInteractionEnabled = YES;
        _blankImageView.hidden = YES;
        WeakSelf
        [self.blankImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(adjuctFloat(230), adjuctFloat(170)));
            make.centerX.equalTo(weakSelf.view);
            make.top.equalTo(weakSelf.myCollectionView.mas_centerY);
        }];
    }
    return _blankImageView;
}

#pragma mark ----- 题主，喜欢，回复信息，转发
- (UIView *)bottomView{
    if (_bottomView == nil) {
        _bottomView = [[UIView alloc] init];
        [self.view addSubview:self.bottomView];

        _nickNameLabel = [[UIButton alloc] init];
        [_nickNameLabel setTitleColor:MainColor forState:0];
        _nickNameLabel.titleLabel.font = CustomUIFont(15);
        _nickNameLabel.titleLabel.textAlignment = 1;
        _nickNameLabel.userInteractionEnabled = YES;
        WeakSelf
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf lookUserInfo];
        }];
        [_nickNameLabel addGestureRecognizer:tap];
        [self.bottomView addSubview:self.nickNameLabel];


        self.distanceLabel = [UILabel new];
        self.distanceLabel.font = CustomUIFont(14);
        self.distanceLabel.textColor = FirstTextColor;
        self.distanceLabel.hidden = YES;
        [self.bottomView  addSubview:self.distanceLabel];
        self.distanceLabel.textAlignment = 1;
        [self.distanceLabel sizeToFit];
        
        
        self.playButton = [UIButton buttonWithType:0];
        [self.playButton setImage:[UIImage imageNamed:@"动画0"] forState:0];
        [self.playButton addTarget:self action:@selector(targetPlayButton) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:self.playButton];
        NSArray *animateNames = @[@"动画0",@"动画1",@"动画2"];
        NSMutableArray * animationImages = [[NSMutableArray alloc] initWithCapacity:animateNames.count];
        for (NSString * animateName in animateNames) {
            UIImage * animateImage = [UIImage imageNamed:animateName];
            [animationImages addObject:animateImage];
        }
        self.playButton.imageView.animationImages = animationImages;
        self.playButton.imageView.animationDuration = 0.7;
        
        
        self.closeButton = [UIButton buttonWithType:0];
        [self.closeButton setImage:[UIImage imageNamed:@"hear_屏蔽"] forState:0];
        [self.closeButton addTarget:self action:@selector(closeButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:self.closeButton];
        [self.closeButton setTitleColor:FirstTextColor forState:0];
        self.closeButton.titleLabel.font = CustomUIFont(13);
        
        self.messageButton = [UIButton buttonWithType:0];
        [self.messageButton setImage:[UIImage imageNamed:@"hear_打招呼"] forState:0];
        [self.messageButton addTarget:self action:@selector(messageButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:self.messageButton];
        
        self.likeButton = [EmitterBtn buttonWithType:0];
        [self.likeButton setImage:[UIImage imageNamed:@"hear_点赞"] forState:0];
        [self.likeButton setImage:[UIImage imageNamed:@"hear_点赞-选中"] forState:UIControlStateSelected];
        [self.likeButton setImage:[UIImage imageNamed:@"hear_点赞-选中"] forState:UIControlStateHighlighted];
        [self.likeButton setImageEdgeInsets:UIEdgeInsetsMake(-7, -7, 0, 7)];
        [self.likeButton addTarget:self action:@selector(likeButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:self.likeButton];
        [self.likeButton setTitleColor:FirstTextColor forState:0];
        self.likeButton.titleLabel.font = CustomUIFont(13);
        CGFloat likeTopPaidng;
        if(kFullWidth == 320){
            likeTopPaidng = adjuctFloat(10);
        }else{
            likeTopPaidng = adjuctFloat(30);
        }
        self.likeButton.frame = CGRectMake(kScreenWidth/2+65, 40+likeTopPaidng+5, 50, 50);

        
        self.lineCoundLabel = [UILabel new];
        self.lineCoundLabel.font = CustomUIFont(13);
        self.lineCoundLabel.textColor = FirstTextColor;
        [self.bottomView  addSubview:self.lineCoundLabel];
        self.lineCoundLabel.frame = CGRectMake(self.likeButton.left-7, self.likeButton.bottom-20, self.likeButton.width, 20);
        self.lineCoundLabel.textAlignment = 1;
        
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(kFullWidth, adjuctFloat(210)));
            make.top.equalTo(weakSelf.view).offset(_myCollectionView.bottom);
            make.left.equalTo(weakSelf.view);
        }];
        

        [_nickNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.bottomView);
            make.height.equalTo(@20);
            make.width.equalTo(@180);
            make.centerX.equalTo(weakSelf.view);
        }];
        
    
        [self.distanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weakSelf.view);
            make.top.equalTo(_nickNameLabel.mas_bottom);
            make.size.mas_equalTo(CGSizeMake(100, 30));
        }];
        
//        [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(weakSelf.distanceLabel);
//            make.left.equalTo(weakSelf.distanceLabel.mas_right);
//            make.size.mas_equalTo(CGSizeMake(30, 30));
//        }];
                [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.equalTo(weakSelf.view);
                    make.top.equalTo(_nickNameLabel.mas_bottom).offset(15 * scaleHeight);
                    make.size.mas_equalTo(CGSizeMake(30, 30));
                }];
        
        [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.view.mas_centerX).offset(-60);
            if(kFullWidth == 320){
                make.top.equalTo(weakSelf.distanceLabel.mas_bottom).offset(adjuctFloat(10));
            }else{
                make.top.equalTo(weakSelf.distanceLabel.mas_bottom).offset(adjuctFloat(30));
            }
            make.size.mas_equalTo(CGSizeMake(50, 50));
        }];
        
        
        [self.messageButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weakSelf.view.mas_centerX);
            make.top.equalTo(weakSelf.closeButton.mas_top);
            make.size.mas_equalTo(CGSizeMake(50, 50));
        }];
        
//        [self.likeButton mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.equalTo(weakSelf.messageButton.mas_right).offset(40);
//            make.top.equalTo(weakSelf.closeButton.mas_top);
//            make.size.mas_equalTo(CGSizeMake(50, 50));
//        }];
    }
    return _bottomView;
}

-(HRPostSoundViewModel *)soundViewModel{
    if (_soundViewModel == nil){
        _soundViewModel = [HRPostSoundViewModel new];
    }
    return _soundViewModel;
}


- (HRMainViewModel *)mainViewModel{
    if (_mainViewModel == nil) {
        _mainViewModel = [[HRMainViewModel alloc] init];
    }
    return _mainViewModel;
}

- (UICollectionView *)myCollectionView{
    if (_myCollectionView == nil) {
        WeakSelf
        RFLayout *layout = [RFLayout new];
        layout.trangeScaleMaxBlock =^(NSInteger index){
            weakSelf.currentIndex = index;
            [self createPlayer];
            if (![[[[NSUserDefaults standardUserDefaults] URLForKey:@"SoundUrl"] absoluteString] length] &&index % 10 ==0 && index!=0){
                UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"" message:@"语音回答 → 展现自信 → 引起共鸣" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"继续浏览" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [cancelAction setValue:SecondTextColor forKey:@"titleTextColor"];
                
                [alertView addAction:cancelAction];
                WeakSelf
                UIAlertAction *enterAction = [UIAlertAction actionWithTitle:@"发表回答" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    HRMainRootModel *model = weakSelf.contentArray[0];
                    HRRecordAudioViewController *recordVC = [HRRecordAudioViewController new];
                    recordVC.isSound = YES;
                    recordVC.title = @"我来回答";
                    recordVC.QuestionID = model.QuestionID;
                    recordVC.soundRemendText = model.QuestionText;
                    [weakSelf.navigationController pushViewController:recordVC animated:YES];
                }];
                [enterAction setValue:BlueColor forKey:@"titleTextColor"];
                [alertView addAction:enterAction];
                [weakSelf presentViewController:alertView animated:YES completion:nil];
            }
            
            if (self.currentIndex != 0 || self.isFirstLoad){
                self.isFirstLoad = YES;
                if (self.currentPlayStatus){
                    [self.streamer play];
                }
            }
        };
        _myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.topView.bottom+adjuctFloat(30), kFullWidth, CGHeightMT(130)) collectionViewLayout:layout];
        _myCollectionView.backgroundColor = [UIColor whiteColor];
        _myCollectionView.delegate = self;
        _myCollectionView.dataSource = self;
        _myCollectionView.showsVerticalScrollIndicator = NO;
        _myCollectionView.showsHorizontalScrollIndicator = NO;
        _myCollectionView.contentInset = UIEdgeInsetsMake(0, (kFullWidth-80)/2, 0, (kFullWidth-80)/2);

    }
    return _myCollectionView;
}


- (HRHearRootTopView *)topView{
    if (_topView == nil) {
        WeakSelf
        HRHearRootTitleTypeView *titleTypeView = [[HRHearRootTitleTypeView alloc] initWithFrame:CGRectMake(0, kTopHeight, kFullWidth, adjuctFloat(60))];
        [self.view addSubview:(self.titleTypeView=titleTypeView)];
        titleTypeView.selectTypeCodeBlock = ^(NSString *code) {
            if (!weakSelf.contentArray.count)return;
            weakSelf.ParentQuestionID = code;
            weakSelf.pIndex = 0;
            weakSelf.topView.currentIndex = 0;
            weakSelf.QuestionID = 0;
            weakSelf.currentIndex = 0;
            //        [weakSelf.topView.tableView scrollToRow:0 inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:YES];
            weakSelf.currentAnswerPage = 0;
            weakSelf.fromSearchPage = 0;
            [weakSelf getContentPeopel:YES andFromSearch:NO];
            [weakSelf.topView.tableView scrollToRow:weakSelf.fromSearchPage inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:YES];
        };
        
        _topView = [[HRHearRootTopView alloc] initWithFrame:CGRectMake(0, titleTypeView.bottom, kFullWidth, adjuctFloat(150))];
        _topView.answerBlock = ^(NSString *QuestionID, NSString *QuestionText) {//回答
            [MobClick event:@"Hearer2"];

            HRRecordAudioViewController *recordVC = [HRRecordAudioViewController new];
            recordVC.isSound = YES;
            recordVC.title = @"我来回答";
            recordVC.QuestionID = QuestionID;
            recordVC.soundRemendText = QuestionText;
            [weakSelf.navigationController pushViewController:recordVC animated:YES];
        };
        
        _topView.showCurrentAnswerPage = ^(NSUInteger currentAnswerPage) { //当前话题页
            [weakSelf.streamer pause];
            weakSelf.currentAnswerPage = currentAnswerPage;
            [weakSelf.myCollectionView reloadData];
//            HRMainRootModel *model = weakSelf.contentArray[weakSelf.currentAnswerPage];
            [self getContentPeopel:YES andFromSearch:NO];
            HRMainRootModel *model = weakSelf.contentArray[0];
//            weakSelf.QuestionID = model.QuestionID;
            if (model.ListSoundArr.count){
                weakSelf.bottomView.hidden = NO;
                weakSelf.blankImageView.hidden = YES;
            }else{
                weakSelf.bottomView.hidden = YES;
                weakSelf.blankImageView.hidden = NO;
            }
        };
    }
    return _topView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    一进入留声机页面就开始转菊花
    [MBProgressHUD showHUDAddedTo:WINDOW animated:YES];
    self.view.backgroundColor = [UIColor whiteColor];
    self.QuestionID = @"0";
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasRecodeSound"]; // 判断注册之后没有录制语音 强制下次打开进录制界面

    self.currentAnswerPage = 0;

    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"主页提示"]){
        self.SortType = 3;
        self.Sex = 2;
        [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"hear_selectSex"];
        [[NSUserDefaults standardUserDefaults] setInteger:self.SortType forKey:@"hear_selectSortType"];

    }else{
        NSInteger hear_selectSex = [[NSUserDefaults standardUserDefaults] integerForKey:@"hear_selectSex"];
        NSInteger hear_selectSortType = [[NSUserDefaults standardUserDefaults] integerForKey:@"hear_selectSortType"];

        if (hear_selectSex == 1){
            self.Sex = 2;
        }else if (hear_selectSex == 2){
            self.Sex = 1;
        }else if (hear_selectSex == 3){
            self.Sex = 0;
        }
        self.SortType = hear_selectSortType;

        
    }
    DDLog(@"   ===============   Enter HRHearViewController viewDidLoad");
    [self setupView];
    [self getGetSoundQuestionParent];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadHearView) name:@"reloadHearView" object:nil];
    
}

- (void)reloadHearView{
//    self.currentIndex = 0;
//    self.pIndex = 0;
//    [self getContentPeopel:YES];
}
#pragma mark ----- 头部导航栏
- (void)setupView{
    DDLog(@" ============== 执行 HRHearViewController/setupView");
    UIButton *titileButton = [UIButton buttonWithType:0];
    titileButton.size = CGSizeMake(100, 30);
//    [titileButton setImage:[UIImage imageNamed:@"hear_search"] forState:0];
    [titileButton setTitle:@"留声机" forState:0];
    [titileButton setImagePositionWithType:SSImagePositionTypeRight spacing:2];
    [titileButton setTitleColor:[UIColor whiteColor] forState:0];
    titileButton.titleLabel.font = CustomUIFont(17);
    [titileButton addTarget:self action:@selector(titileButtonClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titileButton;
    self.titileButton = titileButton;
    
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"HRHearCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"hearIdentifier"];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(0, 0, 14, 14);
    [searchBtn setBackgroundImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *searchBarButton = [[UIBarButtonItem alloc] initWithCustomView:searchBtn];
    
    UIButton *filterBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    filterBtn.frame = CGRectMake(0, 0, 14, 14);
    [filterBtn setBackgroundImage:[UIImage imageNamed:@"筛选"] forState:UIControlStateNormal];
    [filterBtn addTarget:self action:@selector(filter) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *filterBarButton = [[UIBarButtonItem alloc] initWithCustomView:filterBtn];
    
    [self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:searchBarButton,filterBarButton, nil]];
    
//    UIButton *rightButton = [UIButton buttonWithType:0];
//    rightButton.size = CGSizeMake(30, 30);
//    [rightButton setImage:[UIImage imageNamed:@"足迹"] forState:0];
//    [rightButton addTarget:self action:@selector(rightButotnClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *createTopicBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [createTopicBtn addTarget:self action:@selector(selfCreataTopic) forControlEvents:UIControlEventTouchUpInside];
    [createTopicBtn setBackgroundImage:[UIImage imageNamed:@"创建话题"] forState:0];
    createTopicBtn.frame = CGRectMake(0, 0, 12, 12);
    UIBarButtonItem *createTopicBarBtn = [[UIBarButtonItem alloc] initWithCustomView:createTopicBtn];
    [self.navigationItem setRightBarButtonItem:createTopicBarBtn];

//    [JPUSHService setTags:nil alias:USERID fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
//        DDLog(@"iResCode==%d iAlias====%@",iResCode,iAlias);
//    }];
    
    self.contentArray = [NSMutableArray array];
    
    self.pIndex = 0;

}

-(void)selfCreataTopic
{
    
}
#pragma mark ----------- 点击足迹按钮
- (void)rightButotnClick{
    [MobClick event:@"Hearer12"];
    HRHearTopicRootViewController *VC = [HRHearTopicRootViewController new];
    [self.navigationController pushViewController:VC animated:YES];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    HRMainRootModel *model = self.contentArray[0];

    return model.ListSoundArr.count;
}

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HRHearCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hearIdentifier" forIndexPath:indexPath];
    HRMainRootModel *model = self.contentArray[0];
    cell.model = model.ListSoundArr[indexPath.row];
    WeakSelf
    cell.clickIconBlock = ^(){
        weakSelf.currentIndex = indexPath.row;
        [weakSelf lookUserInfo];
    };
    cell.clickNickNameBlock = ^(){
        weakSelf.currentIndex = indexPath.row;
        [weakSelf createPlayer];
        [weakSelf.streamer play];
    };
    
    
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}



- (void)setMusicIsPlaying:(BOOL)musicIsPlaying {
    _musicIsPlaying = musicIsPlaying;
    if (_musicIsPlaying) {
        self.playButton.selected = YES;
    } else {
        self.playButton.selected = NO;
    }
}

#pragma mark 播放按钮
- (void)targetPlayButton{
    self.playButton.selected = !self.playButton.isSelected;
    if (self.playButton.selected){// 播放
        self.currentPlayStatus = YES;
        [self.playButton.imageView startAnimating];
        if (self.streamer){
             [self.streamer play];
            [self.musicDurationTimer setFireDate:[NSDate distantPast]];
        }else{
            [self createPlayer];
            [self.streamer play];
        }
    }else{//暂停
        [self.streamer pause];
        [self.playButton.imageView stopAnimating];
        self.currentPlayStatus = NO;
        [self.musicDurationTimer setFireDate:[NSDate distantFuture]];
    }
}


#pragma mark 切换声音
- (void)cutSound:(NSInteger)index{
    self.playButton.selected = YES;
    if (index == 0){// 上一个
        if (self.currentIndex == 0){
            [MBProgressHUD showMessage:@"已经是第一个声音了" finishBlock:nil];
            return;
        }
        if (_currentIndex == 0 || [self currentIndexIsInvalid]) {
            self.currentIndex = self.contentArray.count - 1;
        } else {
            self.currentIndex--;
        }

        [self createPlayer];
        if (self.currentPlayStatus){
            [self.streamer play];
        }
    }else{//下一个
        if (self.currentIndex == (self.contentArray.count-1)){
            [MBProgressHUD showMessage:@"已经是最后一个声音了" finishBlock:nil];
            return;
        }
        [self checkNextIndexValue];
        [self createPlayer];
        if (self.currentPlayStatus){
            [self.streamer play];
        }
        
    }
}

- (void)likeButtonClick{
    if (self.likeButton.selected) return;
    
    self.likeButton.selected = !self.likeButton.isSelected;
    [self.likeButton starAmimation];
    
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"MomentLocalId"] = self.currentModel.MomentLocalId;
    paramDict[@"LocalId"] = self.currentModel.LocalId;
    paramDict[@"UserLocalId"] = USERID;
    paramDict[@"CreateTime"] = [self getCurrentTime];
    WeakSelf
    [self.mainViewModel postSaveSoundLike:paramDict isSeccess:^(BOOL isSeccess) {
        if (isSeccess){
            weakSelf.currentModel.IsDoLike = @"1";
            weakSelf.likeButton.selected = YES;
            weakSelf.lineCoundLabel.text = [NSString stringWithFormat:@"%d",[self.lineCoundLabel.text intValue]+1];
        }
    }];
    
}
        

- (void)checkNextIndexValue {
    NSInteger lastIndex = self.contentArray.count - 1;
    if (_currentIndex == lastIndex || [self currentIndexIsInvalid]) {
        self.currentIndex = 0;
    } else {
        self.currentIndex++;
    }
}

- (BOOL)currentIndexIsInvalid {
    return _currentIndex >= self.contentArray.count;
}

#pragma 搜索
- (void)searchButtonClick{
    HRSearchUsersViewController *VC = [HRSearchUsersViewController new];
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)getGetSoundQuestionParent{
    WeakSelf
    [self.mainViewModel getGetSoundQuestionParent:nil resultArr:^(NSArray *resultArr) {
        if (resultArr.count){
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.titleTypeView.titleArray = resultArr;
                HRHearTitleTypeModel *model = [resultArr firstObject];
                weakSelf.ParentQuestionID = model.Code;
                [weakSelf getContentPeopel:YES andFromSearch:NO];
            });
        }
    }];
}

#pragma mark 获取声音
- (void)getContentPeopel:(BOOL)isHead andFromSearch:(BOOL)isFromSearch{
    DDLog(@"获取声音---------getContentPeople");
    WeakSelf
    HRMainRootRequestModel *requestModel = [HRMainRootRequestModel new];
    requestModel.PageSize = @"30";     //显示问题回答的个数：唱片分页的每页多少
    requestModel.PageIndex = self.pIndex;
    requestModel.CurrentUserLocalId = USERID;
    requestModel.Sex = self.Sex;
    requestModel.SortType = self.SortType;
    requestModel.StartAge = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentMinValue"];
    requestModel.EndAge = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentMaxValue"];
//    requestModel.QuestionPageIndex = @"0";
    if (self.currentAnswerPage) {
        requestModel.QuestionPageIndex = [NSString stringWithFormat:@"%d",self.currentAnswerPage];
    }
    else
    {
        requestModel.QuestionPageIndex = @"0";
    }
    requestModel.QuestionPageSize = @"1";
    requestModel.QuestionID = self.QuestionID;
    requestModel.ParentQuestionID = self.ParentQuestionID;
    [self.mainViewModel getMainContentParam:requestModel resultArr:^(NSArray *resultArr) {
        
        [MBProgressHUD hideHUDForView:WINDOW animated:YES];
        BOOL isInsert = NO;
        if (resultArr.count || isHead){
            [weakSelf.contentArray removeAllObjects];
            isInsert = YES;
        }else{
            [MBProgressHUD showMessage:@"没有更多声音了" finishBlock:nil];
            isInsert = NO;
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                self.currentIndex = 0;
                self.pIndex = 0;
                [weakSelf getContentPeopel:YES andFromSearch:NO];
            });
        }
        [weakSelf.contentArray addObjectsFromArray:resultArr];

        weakSelf.currentIndex = 0;
//        [weakSelf createPlayer];
        
        dispatch_async(dispatch_get_main_queue(), ^{
//            if (isHead &&weakSelf.contentArray.count){
//                weakSelf.blankImageView.hidden = NO;
//                weakSelf.bottomView.hidden = YES;
//                [weakSelf.myCollectionView reloadData];
//                return;
//            }
            
#pragma warning ----- why
//            if (weakSelf.currentIndex >= weakSelf.contentArray.count || weakSelf.currentAnswerPage >=weakSelf.contentArray.count)                return;
            
            weakSelf.topView.contentArr = weakSelf.contentArray;
//            [weakSelf.topView.contentArr addObject:weakSelf.contentArray[0]];
//            [weakSelf.topView.tableView reloadData];
//            [weakSelf.topView.contentArr addObjectsFromArray:weakSelf.contentArray];
            [weakSelf.streamer pause];
            weakSelf.playButton.selected = NO;
            [weakSelf _cancelStreamer];
            
//            HRMainRootModel *model = weakSelf.contentArray[weakSelf.currentAnswerPage];
            HRMainRootModel *model = weakSelf.contentArray[0];
            
            if (model.ListSoundArr.count){
                weakSelf.currentModel = model.ListSoundArr[0];
            }
            [weakSelf.view addSubview:weakSelf.bottomView];

            [weakSelf setupContentData];          
            [weakSelf.view addSubview:weakSelf.topView];
            [weakSelf.view addSubview:weakSelf.myCollectionView];
            [weakSelf.view addSubview:weakSelf.blankImageView];
            [weakSelf.myCollectionView reloadData];
            if(!model.ListSoundArr.count){
                weakSelf.blankImageView.hidden = NO;
                weakSelf.bottomView.hidden = YES;
            }else{
                weakSelf.blankImageView.hidden = YES;
                weakSelf.bottomView.hidden = NO;
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (isFromSearch && !isHead){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        weakSelf.currentAnswerPage = weakSelf.fromSearchPage;
                        [weakSelf.topView.tableView scrollToRow:weakSelf.fromSearchPage inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:YES];
                        weakSelf.topView.currentIndex = weakSelf.currentAnswerPage;
                        weakSelf.topView.numLabel.text = [NSString stringWithFormat:@"%d/%d",weakSelf.topView.currentIndex+1,weakSelf.topView.contentArr.count];
                    });
                }
            });
            
//            [weakSelf.myCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];

            
        });
        
    }];
}
-(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1)));
}

- (void)createPlayer{
    HRMainRootModel *model = self.contentArray[0];

    if (self.currentIndex >= model.ListSoundArr.count) return;
    self.currentModel = model.ListSoundArr[self.currentIndex];
    
    
    [self setupContentData];
    
    Track *track = [[Track alloc] init];
    track.audioFileURL = [NSURL URLWithString:self.currentModel.SoundUrl];
    @try {
        [self removeStreamerObserver];
    } @catch(id anException){
    }
    
    
    _streamer = nil;
    _streamer = [DOUAudioStreamer streamerWithAudioFile:track];
    
    [self addStreamerObserver];
//    [self.streamer play];
}

- (void)setupContentData{
    
    if ([_currentModel.UserLocalId isEqualToString:USERID]){
//        self.closeButton.enabled = NO;
        self.messageButton.enabled = NO;
    }else{
        self.closeButton.enabled = YES;
        self.messageButton.enabled = YES;
    }

    [self.nickNameLabel setTitle:[NSString stringWithFormat:@"%@",self.currentModel.UserGroup] forState:0];
    NSDictionary *dic = @{NSFontAttributeName:self.nickNameLabel.titleLabel.font};//指定字号
    CGFloat nickNameLabelWidth = [self.nickNameLabel.titleLabel.text boundingRectWithSize:CGSizeMake(self.view.width - 30, 0)/*计算高度要先指定宽度*/ options:NSStringDrawingUsesLineFragmentOrigin |
                   NSStringDrawingUsesFontLeading attributes:dic context:nil].size.width;
    [self.nickNameLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(nickNameLabelWidth+22);
    }];
    
    if ([self.currentModel.Sex intValue] ==1){
        [self.nickNameLabel setImage:[UIImage imageNamed:@"nim_male"] forState:0];
    }else{
        [self.nickNameLabel setImage:[UIImage imageNamed:@"nim_female"] forState:0];
    }
    [self.nickNameLabel setImagePositionWithType:SSImagePositionTypeRight spacing:2];
    self.distanceLabel.text = self.currentModel.ActiveText;
    
    self.likeButton.selected = [self.currentModel.IsDoLike intValue];
    self.lineCoundLabel.text = self.currentModel.LikeCount;
//    [self.likeButton setTitle:self.currentModel.LikeCount forState:0];
//    [self.likeButton setImagePositionWithType:SSImagePositionTypeTop spacing:0];
    
    [self.closeButton setTitle:self.currentModel.CommentCount forState:0];
    [self.closeButton setImagePositionWithType:SSImagePositionTypeTop spacing:0];

//    self.likeButton.enabled = [self.currentModel.IsDoLike intValue];
    
    self.nickNameLabel.imageView.size = CGSizeMake(20, 20);
   WeakSelf
    
    [self.leftLineLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.distanceLabel.mas_left);
    }];
    
    [self.rightLineLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.distanceLabel.mas_right);
    }];
}


- (void)removeStreamerObserver {
    [_streamer removeObserver:self forKeyPath:@"status"];
    [_streamer removeObserver:self forKeyPath:@"duration"];
    [_streamer removeObserver:self forKeyPath:@"bufferingRatio"];
}

- (void)addStreamerObserver {
    [_streamer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:kStatusKVOKey];
    [_streamer addObserver:self forKeyPath:@"duration" options:NSKeyValueObservingOptionNew context:kDurationKVOKey];
    [_streamer addObserver:self forKeyPath:@"bufferingRatio" options:NSKeyValueObservingOptionNew context:kBufferingRatioKVOKey];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == kStatusKVOKey) {
        [self performSelector:@selector(updateStatus)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    } else if (context == kDurationKVOKey) {
        [self performSelector:@selector(updateSliderValue:)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    } else if (context == kBufferingRatioKVOKey) {
        [self performSelector:@selector(updateBufferingStatus)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)updateBufferingStatus {
    
}

- (void)updateSliderValue:(id)timer{
    
}
- (void)_cancelStreamer{
    if (_streamer !=nil) {
        [_streamer pause];
        [_streamer removeObserver:self forKeyPath:@"status"];
        [_streamer removeObserver:self forKeyPath:@"duration"];
        [_streamer removeObserver:self forKeyPath:@"bufferingRatio"];
        _streamer =nil;
    }
}

- (void)updateStatus {
    switch ([_streamer status]) {
        case DOUAudioStreamerPlaying:
            self.musicIsPlaying = YES;
            self.playButton.selected = YES;
            [self.playButton.imageView startAnimating];
            break;
            
        case DOUAudioStreamerPaused:
            self.playButton.selected = NO;
            [self.playButton.imageView stopAnimating];
            break;
            
        case DOUAudioStreamerIdle:
            break;
            
        case DOUAudioStreamerFinished:
            self.playButton.selected = NO;
            [self.playButton.imageView stopAnimating];
            [self.playButton setImage:[UIImage imageNamed:@"动画0"] forState:0];
            [self _cancelStreamer];
            break;
            
        case DOUAudioStreamerBuffering:
            break;
            
        case DOUAudioStreamerError:
            break;
    }
}


# pragma mark - Handle Music Slider


-(void)dealloc{
    self.streamer = nil;
}



- (void)lookUserInfo{
    if (self.contentArray.count){
        HRMainRootModel *listModel = self.contentArray[0];
        HRMainRootModel *model = listModel.ListSoundArr[0];

        if (self.currentIndex >= listModel.ListSoundArr.count) return;
        
        HRDynamicViewController *infoVC = [HRDynamicViewController new];
        infoVC.currentUserID = model.UserLocalId;
        
        [self.navigationController pushViewController:infoVC animated:YES];
    }
    
}


- (void)closeButtonClick{
    WeakSelf
    if (!self.currentModel.MomentLocalId.length){
        self.currentModel.MomentLocalId = self.currentModel.LocalId;
    }

//    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"isShowRecordView"]){
//        [self saveSoundRecord];
//    }else{
//        [HRShowRecordView showRecordView:^{
//            [weakSelf saveSoundRecord];
//        } andCancelBlock:^{
//
//        }];
//    }
    
    HRFollowDyanmicInfoViewController *infoVC = [HRFollowDyanmicInfoViewController new];
    infoVC.dynamicID = self.currentModel.MomentLocalId;
    [self.navigationController pushViewController:infoVC animated:YES];

}

- (void)saveSoundRecord{
    WeakSelf
    HRSaveSoundRecord *soundRequestModel = [HRSaveSoundRecord  new];
    soundRequestModel.CurrentUserLocalId = USERID;
    soundRequestModel.VisitedUserLocalId = self.currentModel.UserLocalId;
    soundRequestModel.SoundUrl = weakSelf.currentModel.SoundUrl;
    soundRequestModel.CreateTime = [weakSelf getCurrentTime];
    [weakSelf.soundViewModel saveSoundRecordParam:soundRequestModel isSeccess:^(BOOL isSeccess) {
        if (isSeccess){
            HRMainRootModel *model = weakSelf.contentArray[weakSelf.currentAnswerPage];
            [model.ListSoundArr removeObjectAtIndex:weakSelf.currentIndex];
            
            if (model.ListSoundArr.count){
                weakSelf.bottomView.hidden = NO;
                weakSelf.blankImageView.hidden = YES;
                [weakSelf.myCollectionView reloadData];
                [weakSelf cutSound:1];
            }else{
                weakSelf.bottomView.hidden = YES;
                weakSelf.blankImageView.hidden = NO;
                [weakSelf.myCollectionView reloadData];
                [weakSelf.streamer pause];
            }
            
        }
    }];
}

- (void)messageButtonClick{
    [MobClick event:@"Hearer3"];

    HRUpdataUserInfoModel*model = [HRUpdataUserInfoModel modelWithJSON:USERINFO];

    HRMainRootModel *listModel = self.contentArray[0];
    
//    if (self.currentModel.MomentLocalId.length){
//        HRFollowDyanmicInfoViewController *infoVC = [HRFollowDyanmicInfoViewController new];
//        infoVC.dynamicID = self.currentModel.MomentLocalId;
//        [self.navigationController pushViewController:infoVC animated:YES];
//    }else{
        EaseMessageViewController *messgaeVC = [[EaseMessageViewController alloc] initWithConversationChatter:self.currentModel.UserLocalId conversationType:EMConversationTypeChat];
        messgaeVC.otherNickNameStr = self.currentModel.NickName;
        messgaeVC.otherIconStr = self.currentModel.UserPictureBackgroundColor;
        messgaeVC.otherIconName = self.currentModel.UserPictureName;
        messgaeVC.title = self.currentModel.NickName;
        messgaeVC.isSayHello = YES;
        [self.navigationController pushViewController:messgaeVC animated:YES];
//    }
}


- (void)titileButtonClick{
    
    WeakSelf
    [HRSearchToolView showSearchToolView:^(NSDictionary *contentDict) {
        weakSelf.Sex = [contentDict[@"Sex"] intValue];
        weakSelf.SortType = [contentDict[@"SortType"] intValue];
        weakSelf.pIndex = 0;
        weakSelf.topView.currentIndex = 0;
        weakSelf.QuestionID = 0;
        weakSelf.currentIndex = 0;
//        [weakSelf.topView.tableView scrollToRow:0 inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:YES];
        [weakSelf getContentPeopel:YES andFromSearch:YES];
        weakSelf.fromSearchPage = weakSelf.currentAnswerPage;
        
        [MobClick event:@"Hearer1"];

    }];

    
}

- (NSString *)getCurrentTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    return [formatter stringFromDate:[NSDate date]];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}


-(void)viewWillDisappear:(BOOL)animated{
    [self.streamer pause];
    self.playButton.selected = NO;
    [super viewWillDisappear:animated];
}

-(void)viewWillAppear:(BOOL)animated{
    [self newUserGuide];
    [super viewWillAppear:animated];
}


- (void)newUserGuide{
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"主页提示"])return;
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"主页提示"];

    
    CGRect frame = [UIScreen mainScreen].bounds;
    UIView * bgView = [[UIView alloc]initWithFrame:frame];
    bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.85];
    [[UIApplication sharedApplication].keyWindow addSubview:bgView];
    
    UIImageView *showImageView = [[UIImageView alloc] initWithFrame:CGRectMake((kFullWidth-adjuctFloat(344))/2, (kFullHeight-adjuctFloat(374))/2, adjuctFloat(344), adjuctFloat(374))];
    showImageView.image = [UIImage imageNamed:@"留声机_引导"];
    [bgView addSubview:showImageView];
    
    UIButton *enterButton = [UIButton buttonWithType:0];
    enterButton.frame = CGRectMake((bgView.width-100)/2, showImageView.bottom+30, 100, 37);
    [enterButton setImage:[UIImage imageNamed:@"朕知道了"] forState:0];
    [enterButton addTarget:self action:@selector(enterButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:enterButton];

}



- (void)enterButtonClick:(UIButton *)button {
    UIView * view = button.superview;
    [view removeFromSuperview];
    [view removeAllSubviews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
